package com.sc;

import javax.annotation.processing.Processor;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author sc
 * Created on  2017/12/14
 *
 * 多线程Reactor模式
 */
public class NioMultiServer {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(8080));
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);


        while(true){
            if(selector.selectNow()<0){
                continue;
            }
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = keys.iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                if(key.isAcceptable()){
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel socketChannel = channel.accept();
                    socketChannel.configureBlocking(false);
                    SelectionKey readKey = socketChannel.register(selector,SelectionKey.OP_READ);
                    readKey.attach(new Processor());
                }else  if(key.isReadable()){
                    Processor processor = (Processor) key.attachment();
                    processor.process(key);
                }
            }
        }

    }


    public static class Processor{
        public static final ExecutorService service = Executors.newFixedThreadPool(16);

        public void process(SelectionKey key) {
            service.submit(()->{
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                SocketChannel socketChannel = (SocketChannel) key.channel();
                try {
                    int count = socketChannel.read(byteBuffer);
                    if(count<0){
                        socketChannel.close();
                        key.cancel();
                        return null;
                    }else if(count==0){
                        return null;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            });
        }
    }
}
